<?php

namespace app\store\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\store\model\User
     */
    protected $model = null;
    protected $grouplist = [];
    //用户分组
    protected $user_group_model = null;
    //店铺模型
    protected $shop_model = null;
    //卡项模型
    protected $order_item_model = null;
    //优惠券领取模型
    protected $coupon_receive_model = null;
    //标签模型
    protected $tag_model = null;
    //标签用户关系模型
    protected $tag_user_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\store\model\User;
        $this->user_group_model = new \app\store\model\UserGroup;
        $this->shop_model = new \app\store\model\store\Shop;
        $this->order_item_model = new \app\store\model\wanlshop\OrderItem;
        $this->coupon_receive_model = new \app\store\model\wanlshop\CouponReceive;
        $this->tag_model = new \app\store\model\wanlshop\Tag;
        $this->tag_user_model = new \app\store\model\wanlshop\TagUser;

        $this->grouplist = $this->user_group_model->order('id desc')->where('status','normal')->select();
        $groupdata = [];
        foreach ($this->grouplist as $k => $v) {
            $groupdata[$v->id] = ['id'=>$v->id,'name' => $v->name];
        }

        $this->view->assign("groupList", $groupdata);
        
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group,shop,juser')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
       
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\store\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign('shopList', build_select('row[shop_id]', \app\store\model\wanlshop\Shop::column('id,shopname'), $row['shop_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign('juserList', build_select('row[juser_id]', \app\store\model\User::column('id,nickname'), $row['juser_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign('marketingList', build_select('row[marketing]', \app\store\model\staff\Staff::column('id,name'), $row['marketing'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 拉黑用户
     */
    public function disableuser($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if($row['status'] == 'normal'){
            $result = $this->model->where('id',$ids)->update(['status'=>'hidden']);
            if(!$result){
                $this->error('操作失败，请稍后重试！');
            }
        }

        $this->success();
    }

     /**
     * 详情
     */
    public function detail($ids = null){
        if ($this->request->isPost()) {
            $this->token();
        }

        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $group_row = $this->user_group_model->where('status','normal')->find($row['group_id']);

        $row['createtime'] = date('Y-m-d H:i:s',$row['createtime']); 

        $juser_user = $this->model->where('id',$row['juser_id'])->value('nickname');

        //推荐人/客户来源
        $row['juser_user'] = empty($juser_user)?'暂无':$juser_user;

        //所属门店
        $shop_name = $this->shop_model->where('user_id',$row['shop_id'])->value('shopname');

        $row['shop_name'] = empty($shop_name)?'暂无':$shop_name;
        
        //用户标签
        $user_tags = $this->tag_user_model->where('user_id',$ids)->with('Tag')->select();

        $this->assign('userData',$row);

        $this->assign('userTags',$user_tags);

        $this->assign('groupName',$group_row?$group_row['name']:'');

        $this->assignconfig('user_id', $ids);

        //卡项
        $order_item_list = $this->order_item_model->where('user_id',$ids)->order('createtime desc')->limit(3)->select();
        $order_item_count = count($order_item_list);
        if ($order_item_count > 0) {
            foreach ($order_item_list as &$value) {
                $_shop_name = $this->shop_model->where('id',$value['shop_id'])->value('shopname');
                $value['shop_name'] = empty($_shop_name)?'无':$_shop_name;
                if($value['validity'] == 0){
                    $value['validitytime'] = '永久有效';
                }
            }
        }

        $this->assignconfig('user_id', $ids);
        $this->view->assign("orderItemList", $order_item_list);
        $this->view->assign("orderItemCount", $order_item_count);

        //优惠券领取
        $where = ['user_id'=>$ids];
        $coupon_list = $this->coupon_receive_model->where($where)->order('createtime desc')->limit(3)->select();
        $coupon_count = count($coupon_list);
        if ($coupon_count > 0) {
            foreach ($coupon_list as &$_value) {
                $_shop_name = $this->shop_model->where('id',$_value['shop_id'])->value('shopname');
                $_value['shop_name'] = empty($_shop_name)?'无':$_shop_name;
            }
        }

        
        $this->view->assign("couponList", $coupon_list);
        $this->view->assign("couponCount", $coupon_count);



        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function addusertag($ids = null)
    {   
        if (false === $this->request->isPost()) {
            //未分组标签
            $group_0 = [];
            //充值客户标签
            $group_1 = [];
            //客户等级标签
            $group_2 = [];
            //用户已选择标签列表
            $user_tags_list = [];
            
            //用户已选择标签
            $where = ['user_id'=>$ids];
            $user_tags = $this->tag_user_model->where($where)->column('tag_id');
            $tegs_count = count($user_tags);

            $where = ['status'=>'normal'];
            $all_tags = $this->tag_model->where($where)->field('id,name,group')->select();

            if (count($all_tags)>0) {
                foreach ($all_tags as $key => $value) {
                    if($value['group'] == 0){
                        $group_0[] = $value;
                    }elseif ($value['group'] == 1) {
                        $group_1[] = $value;
                    }elseif ($value['group'] == 2) {
                        $group_2[] = $value;
                    }

                    if($tegs_count > 0 && in_array($value->id, $user_tags)){
                        $user_tags_list[] = $value;
                    }
                }
            }

            $this->view->assign("group0", $group_0);
            $this->view->assign("group1", $group_1);
            $this->view->assign("group2", $group_2);
            $this->view->assign("usertags", $user_tags);
            $this->view->assign("usertagslist", $user_tags_list);
            $this->view->assign("tagscount", $tegs_count);
            $this->view->assign("user_id", $ids);

            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $user_id = $params['user_id'];

        $tag_ids = isset($params['tag_id'])?$params['tag_id']:[];

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->tag_user_model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->tag_user_model->validateFailException()->validate($validate);
            }
            $data = [];
            $del_data = [];
            $user_tags = $this->tag_user_model->where('user_id',$user_id)->column('tag_id');

            //取消的tag删除掉
            if (count($user_tags)>0) {
                foreach ($user_tags as $_key => $_value) {
                    if (!in_array($_value,$tag_ids)) {
                        $del_data[] = $_value;
                        $res = $this->tag_user_model->where(['user_id'=>$user_id,'tag_id'=>$_value])->delete();
                    }
                }
            }

            if(count($tag_ids) > 0){
                foreach ($tag_ids as $key => $value) {
                    $condition = ['user_id'=>$user_id,'tag_id'=>$value];
                    $info = $this->tag_user_model->where($condition)->find();
                    if (empty($info)) {
                        $data[] = $condition;
                    }
                }

                $result = $this->tag_user_model->allowField(true)->saveAll($data);
            }else{
                $result = true;
            }
            
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function addtag()
    {
        if (true === $this->request->isPost()) {
            $params = trim($this->request->post('tag_name'));

            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            $exist_tag = $this->tag_model->where('name',$params)->find();
            if ($exist_tag) {
                $this->error(__('当前标签已存在'));
            }

            $data = ['name'=>$params];
            $result = $this->tag_model->save($data);

            if ($result) {
                $this->success();
            }else{
                $this->error(__('保存失败'));
            }

        }


        $this->success();
    }

    public function addusercommontag()
    {
        if (true === $this->request->isPost()) {
            $user_id = $this->request->post('user_id');
            $tag_name = trim($this->request->post('tag_name'));

            if (empty($user_id) || empty($tag_name)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            $exist_tag = $this->tag_model->where('name',$tag_name)->find();
            if ($exist_tag) {
                $this->error(__('当前标签已存在'));
            }

            Db::startTrans();
            try {
                $data = ['name'=>$tag_name];
                $res = $this->tag_model->save($data);
                $tag_id = $this->tag_model->getLastInsID();
                if ($res && $tag_id) {
                    $data = ['tag_id'=>$tag_id,'user_id'=>$user_id];
                    $result = $this->tag_user_model->save($data);
                }
                
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($res === false || $result === false) {
                $this->error(__('No rows were inserted'));
            }
            $this->success();
        }
        $this->success();
    }

}
